const Upyun = require('upyun');
const { Service, Client } = Upyun;
const path=require('path');
const fs = require("fs");
const ora = require('ora');
const spinner = ora();
const chalk = require('chalk');
// https://github.com/upyun/node-sdk
// 需要填写自己的服务名，操作员名，密码
const config = require('../config.json')
const serviceName = config['upyun-serviceName']
const operatorName = config['upyun-operatorName']
const password = config['upyun-password']
const remoteHOST = config['upyun-remoteHOST']

const service = new Service(serviceName, operatorName, password)
const client = new Client(service);


const SupportSuffix = ['.jpg','.jpeg','.png','.gif'];
const UnSupportFile = ['node_modules','.DS_Store','.git','.vscode'];
const extnameMap = {
 '.jpg':'jpg',
 '.jpeg':'jpg',
 '.png':'png',
 '.webp':'webp',
 '.gif':'webp',
};

//全局变量
let UploadDone=0;
let UploadIng=0;
let PATH =''; //入口文件夹
let Quality =''; //压缩质量
let IsWebp = false; //转化成webp
let UploadFile = ''; //上传到云端文件夹的目录

/**
 * 主入口
 */
async function main(cmd){
       
    PATH = process.cwd()+(cmd.path?('/'+cmd.path):'');

    Quality = parseInt(cmd.quality,10) || 70; 
    if(Quality<10) Quality = Quality*10; //默认是百分制，也可以支持十分制
    if(Quality>90) Quality = 90;

    IsWebp = !!cmd.webp;
    UploadFile = (cmd.uploadfile||Date.now()).toString();

    console.log(chalk.green(`读取文件目标文件夹: ${PATH}`))
    console.log(chalk.green(`图片压缩质量: ${Quality}`))
    console.log(chalk.green(`是否转换成webp: ${IsWebp}`))
    console.log(chalk.green(`上传到云端文件夹: ${UploadFile}`))

    spinner.start();

    client.makeDir(UploadFile).then(()=>{
        compress(PATH);
    })

} 

function compress(imgpath){
    fs.readdir(imgpath, function(err, files){     
        if(err){
            console.log('error' + err);
            return;
        }
        //console.log('files:' + files);
        files.forEach(function(file){
            var imgName = imgpath + '/' + file;
            fs.stat(imgName, async function(err, stat){
                if(err){console.log(err); return;}
                //过滤不支持的文件
                if(UnSupportFile.includes(file)) return;
                //如果是文件夹遍历
                if(stat.isDirectory()){        
                    compress(imgName);
                }else{ 
                    //过滤不支持的后缀
                    if(!SupportSuffix.includes(path.extname(file))) return;
                    // console.log('文件:' + imgName);
                        uploadImgToUpyun(imgName)
                }               
            });

        });

    });
}

function uploadImgToUpyun(localFile){
        UploadIng++
        //参数 http://docs.upyun.com/cloud/image/#function
        var params = { 'x-gmkerl-thumb': `/format/${IsWebp?'webp':extnameMap[path.extname(localFile)]}/quality/${Quality}`}
        let remoteFile = UploadFile+'/'+localFile.replace(process.cwd()+'/','').replace(/\//g,'-');
        client.putFile(remoteFile, fs.createReadStream(localFile), params).then(res=>{
            spinner.text = chalk.green(remoteFile+' 上传完成！');
        }).catch(error=>{
            console.log(chalk.red(remoteFile+' 上传失败： '+error))
        }).finally(()=>{
            UploadDone++
            getResultList();
        })
}

function getResultList() {
    if(UploadIng===UploadDone){
        client.listDir(UploadFile).then(function(data) {
            spinner.succeed(chalk.green(`all upload completed!√\n`));
            data.files.forEach(i=>console.log(chalk.blue('http://'+remoteHOST+'/'+UploadFile+'/'+i.name)))
        })
    }
     
}

module.exports = main;
// process.on('SIGINT',function (){   console.log('SIGINT!');});
// process.on('SIGTERM',function (){   console.log('SIGTERM!');});
// process.on('exit', function (){  console.log('exit!');});
